package com.ifinc.common.web.frame;

import com.ifinc.common.web.controller.CentralControler;
import com.ifinc.common.web.controller.SessionMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 负责Http的参数转换，将http的数据转化成Map
 *
 * @author luotao
 * @version 1.0 2013-06-09
 */

public class HttpTransform {

    final Logger log = LoggerFactory.getLogger(HttpTransform.class);

    /**
     * 将session中的数据转化成Map
     *
     * @param httpSession
     * @return
     */
    public SessionMap<String, Object> transformSession(HttpSession httpSession) {
        SessionMap<String, Object> sessionMap = new SessionMap<String, Object>();
        Enumeration e = httpSession.getAttributeNames();
        while (e.hasMoreElements()) {
            String key = (String) e.nextElement();
            Object value = httpSession.getAttribute(key);
            sessionMap.put(key, value);
        }
        log.debug("session to map,map:" + sessionMap);
        return sessionMap;
    }

    /**
     * 将Map中的参数放到session中
     *
     * @param session
     * @param sessionMap
     */
    public void putValueToSession(HttpSession session, Map<String, Object> sessionMap) {
        Map<String, Object> map = (Map<String, Object>) sessionMap;
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            session.setAttribute(entry.getKey(), entry.getValue());
        }
    }

    /**
     * 提取request中的参数，转化成Map返回
     *
     * @param req
     * @return
     */
    public Map<String, String> makeParamMap(HttpServletRequest req) {
        Map<String, String> map = new LinkedHashMap<String, String>();
        Enumeration e = req.getParameterNames();
        while (e.hasMoreElements()) {
            String key = (String) e.nextElement();
            String value = req.getParameter(key);
            map.put(key, value);
        }
        log.debug("request param:" + map);
        return map;
    }

    /**
     * 提取reqest的Header中的参数，转化成Map返回
     *
     * @param req
     * @return
     */
    public Map<String, String> makeHeaderParam(HttpServletRequest req) {
        Map<String, String> map = new LinkedHashMap<String, String>();
        Enumeration e = req.getHeaderNames();
        while (e.hasMoreElements()) {
            String key = (String) e.nextElement();
            String value = req.getHeader(key);
            map.put(key, value);
        }
        log.debug("request header:" + map);
        return map;
    }

    public void putMap2ReqAttr(Map<String, Object> result, HttpServletRequest req) {
        for (Map.Entry<String, Object> entry : result.entrySet()) {
            req.setAttribute(entry.getKey(), entry.getValue());
        }
    }
}
